package lbs;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import object.Restaurant;

import service.CommonServlet;

public class GetRestaurants extends CommonServlet {
	
	@Override
	protected void execute(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try
		{
			float longitude = Float.parseFloat(request.getParameter("longitude"));
			float latitude = Float.parseFloat(request.getParameter("latitude"));
			float range = Float.parseFloat(request.getParameter("range"));
			String sql = "select restaurant_info.id, restaurant_info.city, restaurant_info.longitude, restaurant_info.latitude, restaurant_info.recommend_dishes, r_products.name, r_products.manufacturer_address, r_products.manufacturer_phone from restaurant_info,r_products ";
			sql+="where restaurant_info.longitude > ? and restaurant_info.longitude < ? ";
			sql+="and restaurant_info.latitude > ? and restaurant_info.latitude < ? ";
			sql+="and restaurant_info.id = r_products.id order by rand() limit 30";
			PreparedStatement pstmt = mConnection.prepareStatement(sql);
			pstmt.setFloat(1, longitude-range);
			pstmt.setFloat(2, longitude+range);
			pstmt.setFloat(3, latitude-range);
			pstmt.setFloat(4, latitude+range);
			
			ResultSet rs = pstmt.executeQuery();
			List<Restaurant> restaurants = new ArrayList<Restaurant>();
			while(rs.next())
			{
				Restaurant restaurant = new Restaurant();
				restaurant.setId(rs.getString("restaurant_info.id"));
				restaurant.setCity(rs.getString("restaurant_info.city"));
				restaurant.setLongitude(rs.getFloat("restaurant_info.longitude"));
				restaurant.setLatitude(rs.getFloat("restaurant_info.latitude"));
				restaurant.setName(rs.getString("r_products.name"));
				restaurant.setRecommend(rs.getString("restaurant_info.recommend_dishes"));
				restaurant.setAddress(rs.getString("r_products.manufacturer_address"));
				restaurant.setPhone(rs.getString("r_products.manufacturer_phone"));
				restaurants.add(restaurant);
			}
			if(!restaurants.isEmpty())
				sendObject(restaurants, response);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * Constructor of the object.
	 */
	public GetRestaurants() {
		super();
	}

}
